<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .slider-bar {
        position: absolute;
        left: 50%;
        top: 300px;
        margin-left: 600px;
        width: 45px;
        height: 130px;
        background-color: pink;
    }
    
    .w {
        width: 1200px;
        margin: 10px auto;
    }
    
    .header {
        height: 150px;
        background-color: purple;
    }
    
    .banner {
        height: 250px;
        background-color: skyblue;
    }
    
    .main {
        height: 1000px;
        background-color: yellowgreen;
    }
    
    span {
        display: none;
        position: absolute;
        bottom: 0;
        cursor: pointer;
    }
</style>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        var bannerTop = banner.offsetTop;
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        var goBack = document.querySelector('.goBack');
        var main = document.querySelector('.main');
        var mainTop = main.offsetTop;
        document.addEventListener('scroll', function() {
            if (window.pageYOffset >= bannerTop) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = '300px';
            }
            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }
        });
        goBack.addEventListener('click', function() {
            // window.scroll(0, 0);
            animate(window, 0);
        });

        function animate(obj, target, callback) { //callback为一个形参 你实参传过来的是什么就是什么，可以是一个函数
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                //step 为步长值
                var step = (target - window.pageYOffset) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (window.pageYOffset == target) {
                    clearInterval(obj.timer);
                    // if (callback) {
                    //     callback();
                    // }
                    callback && callback();
                }
                // obj.style.left = window.pageYOffset + step + 'px';
                window.scroll(0, window.pageYOffset + step);
            }, 15);
        }
    </script>
</body>

</html>